package com.heima.app.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author shkstart
 * @create 2022-12-30-22:47
 */

/**
 * token的认证过滤器
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 具体过滤逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求实例
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应实例
        ServerHttpResponse response = exchange.getResponse();
        //3.获取请求路径
        String path = request.getURI().getPath();
        //4.如果是登录请求则放行
        if (path.equals("/user/api/v1/login/login_auth/")){
            return chain.filter(exchange);
        }
        //5.获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        //6.如果token为空响应401
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //7.如果token是非法响应401
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int result = AppJwtUtil.verifyToken(claimsBody);
        if (result == 0){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //8.响应放行
        return chain.filter(exchange);
    }

    /**
     * 执行优先级的方法，值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
